﻿using UnityEngine;
using System.Collections;
using System;

public class UIUtil : MonoBehaviour {
    public static void setListener(String BtnName, UIEventListener.VoidDelegate fun) {
        GameObject obj = GameObject.Find(BtnName);
        if(obj != null) {
            var uIEventListener = UIEventListener.Get(obj).onClick = fun;
        } else {
            Debug.LogError("not find "+ BtnName);
        }
    }

    public static void removeAll(UIGrid listView) {
        var v = listView.GetChildList().Count;
        for(int i = 0; i < v; i++) {
            Transform child = listView.GetChild(i);
            listView.RemoveChild(child);
            Destroy(child.gameObject);
        }
        listView.Reposition();
    }
    public static void AddItem(UIGrid listView, String nick, String score, String uid, String url, int index, UIEventListener.VoidDelegate itemOnclick) {
        GameObject o = (GameObject)Instantiate(Resources.Load("ItemListView"));
        AddItem("ItemListView", listView, nick,  score,  uid,  url,  index,  itemOnclick);
    }
    public static void AddItem(String itemSharePreName,UIGrid listView, String nick, String score, String uid, String url, int index, UIEventListener.VoidDelegate itemOnclick) {
        GameObject o = (GameObject)Instantiate(Resources.Load(itemSharePreName));
        o.name = "item" + index;
        //GameObject root = GameObject.Find("GameObject");       
        GameObject avator = o.transform.Find("Avatar").gameObject;
        avator.name = "avator" + index;
        o.transform.Find("Name").GetComponent<UILabel>().text = nick;
        o.transform.Find("Score").GetComponent<UILabel>().text = score;
        UIUtil.setListener("avator" + index, itemOnclick);
        //Debug.Log(nick);
        listView.AddChild(o.transform);
        GameObject item = GameObject.Find(o.name);
        item.transform.localPosition = new Vector3(0, 0, 0);
        item.transform.localScale = new Vector3(1, 1, 1);
        listView.Reposition();
        GameObject texture = o.transform.Find("Texture").gameObject;
        Debug.Log("texture:" + texture.transform);
        UITexture headerImg = texture.GetComponent<UITexture>();
        ImageLoader.getInstance().load(headerImg, url);
    }
}
